﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

namespace Utilities
{
    /// <summary>
    /// JSON序列化和反序列化辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 反序列化JSON（将JSON转换为实体对象或实体对象集）
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T JSON2T<T>(string jsonStr)
        {
            JavaScriptSerializer Seriallizer = new JavaScriptSerializer();
            return Seriallizer.Deserialize<T>(jsonStr);
        }

        /// <summary>
        /// 将实体对象转换为JSON字符串
        /// </summary>
        /// <param name="obj">实体对象</param>
        /// <returns></returns>
        public static string T2JSON(object obj)
        {
            JavaScriptSerializer Seriallizer = new JavaScriptSerializer();
            string result = Seriallizer.Serialize(obj);
            //替换Json的Date字符串
            string p = @"\\/Date\(-{0,1}\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(p);
            result = reg.Replace(result, matchEvaluator);
            return result;
        }

        /// <summary>
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            Regex reg = new Regex(@"-{0,1}\d+");
            string x = reg.Match(m.Groups[0].Value).Value;
            dt = dt.AddMilliseconds(long.Parse(x));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }

        /// <summary>
        /// DataTable转JSON
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>JSON字符串</returns>
        public static string DataTable2JSON(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            JsonString.Append("[");
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {

                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }

            }
            JsonString.Append("]");
            return JsonString.ToString();
        }
        //#endregion
    }
}
